import dayjs from "dayjs";
import { Ref, computed, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import CommonHook from "@/hook/commonHook";
import { getListApi, getPageStaticApi, listByBusinessIdApi } from "@/api/waybillManagement/businessWaybill";
import { shippingApi, signingApi, outWarehouseApi, statisticsDataApi, foutboundShipmentsApi, recoverShipmentApi } from "@/api/waybillManagement/customerServiceWaybill";
import { message as Message, Modal } from "ant-design-vue";
import { turnShipmentWarehouseApi } from "@/api/waybillManagement/customerServiceWaybill";

export default function OperationHook(state: {
  activeKey: Ref<string>;
  searchForm: CustomerServiceWaybill.SearchForm;
  tableData: Ref<CustomerServiceWaybill.ListRows[]>;
  drawerOpts: Base.DrawerOpts;
  dialogOpts: Base.DialogOpts;
  loading: Ref<boolean>;
  tableRef: any;
  saPageInfo: Base.GeneraDataType;
  pageStat: Base.GeneraDataType;
}) {
  const { activeKey, searchForm, tableData, drawerOpts, loading, tableRef, saPageInfo, dialogOpts, pageStat } = state;
  const selectRows = computed<Array<ClientWaybillManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { getNoZeroKey } = CommonHook();
  const getData = async () => {
    const params = {
      ...getParams(),
      saPageInfo: saPageInfo.value
    };
    loading.value = true;
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
          saPageInfo.value = data.saPageInfo || {};
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const pageStateic = () => {
    const params = getParams();
    loading.value = true;
    return getPageStaticApi({ ...params, statusList: [5, 6, 7, 8, 9, -5, 0, -2] })
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          Object.assign(pageStat.value, {
            5: data[5],
            6: data[6],
            7: data[7],
            8: data[8],
            9: data[9],
            "-5": data[-5],
            0: data[0],
            "-2": data[-2]
          });

          activeKey.value = String(getNoZeroKey(pageStat.value, ["5", "6", "7", "8", "9", "-5", "0", "-2"]));
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const getParams = () => {
    const {
      keyWordsList,
      waybillNumList,
      fbaNumberList,
      transferOrderNumberList,
      bizIdList,
      followIdList,
      channelIdList,
      markList,
      notMark,
      customerIdList,
      makeInvoiceStatus,
      zipCode,
      countryRegionIdList,
      customsTaxesTypeList,
      customsDeclarationType,
      innerRemark,
      remark,
      depositTime,
      createdTime,
      warehouseCodeList,
      warehousePropertyList,
      pageNum,
      pageSize,
      companyIds,
      outWarehouseBrokerIds,
      outWarehouseTime,
      warehouseNameList,
      pushOrderSuccess,
      questionType,
      beforePageNum,
      mergeNoList
    } = searchForm;
    const params: Parameters<typeof getListApi>[0] = {
      mergeNoList: [],
      waybillNumList: [],
      keyWordsList: [],
      fbaNumberList: [],
      transferOrderNumberList: [],
      bizIdList,
      followIdList,
      channelIdList,
      warehouseCodeList,
      warehousePropertyList,
      remark,
      markList,
      notMark,
      customerIdList,
      makeInvoiceStatus,
      zipCode,
      countryRegionIdList,
      customsTaxesTypeList,
      customsDeclarationType,
      innerRemark,
      questionType,
      startTime: createdTime?.length ? dayjs(createdTime[0]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      endTime: createdTime?.length ? dayjs(createdTime[1]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      depositStartTime: depositTime?.length ? dayjs(depositTime[0]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      depositEndTime: depositTime?.length ? dayjs(depositTime[1]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      outWarehouseStartTime: outWarehouseTime?.length ? dayjs(outWarehouseTime[0]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      outWarehouseEndTime: outWarehouseTime?.length ? dayjs(outWarehouseTime[0]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      pageNum,
      pageSize,
      companyIds,
      outWarehouseBrokerIds,
      warehouseNameList,
      pushOrderSuccess,
      beforePageNum,
      statusList: [Number(activeKey.value)]
    };
    if (waybillNumList)
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");

    if (keyWordsList)
      params.keyWordsList = keyWordsList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (fbaNumberList)
      params.fbaNumberList = fbaNumberList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (transferOrderNumberList)
      params.transferOrderNumberList = transferOrderNumberList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (mergeNoList)
      params.mergeNoList = mergeNoList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (channelIdList.length) {
      params.channelIdList = channelIdList.map((t: any) => t[t.length - 1]);
    }
    if (searchForm.sort) {
      params.order = searchForm.order;
      params.sort = searchForm.sort;
    }
    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    searchForm.pageNum = 1;
    getData();
  };

  //流程状态
  const statusHandle = (status: number) => {
    // 2出库 3出运 4签收     出仓单独控制
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    const params: CustomerServiceWaybill.StaHandle = {
      idList: selectRows.value.map((t: any) => t.id)
    };
    let request: any;

    if (status === 2) {
      request = outWarehouseApi;
    }

    if (status === 3) {
      request = shippingApi;
    }

    if (status === 4) {
      request = signingApi;
    }

    request(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Message.success(data);
        searchHandle();
      }
    });
  };

  //出库
  const outOfWarehouseHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    Modal.confirm({
      title: "系统将会为所选择的运单创建一个出仓单,确认继续吗?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        foutboundShipmentsApi({ idList: selectRows.value.map((t: any) => t.id) }).then((res: any) => {
          const { code, data } = res;
          if (code === 200) {
            Message.success(data);
            searchHandle();
          }
        });
      }
    });
  };

  // 获取统计数据
  const getStatisticsDataFn = () => {
    const params: any = {
      ...getParams(),
      saPageInfo: saPageInfo.value
    };
    if (selectRows.value.length) params.idList = selectRows.value.map((t: CustomerServiceWaybill.ListRows) => t.id);
    return statisticsDataApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        dialogOpts.passData = data || {};
      }
    });
  };

  const requestFn = () => {
    return listByBusinessIdApi({ businessId: drawerOpts.passData?.id, sysModule: "运单管理" });
  };

  //海外仓运单
  const turnTurnShipmentWarehouseHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    Modal.confirm({
      title: "确认将所选择的所有运单转至到海外仓吗?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        turnShipmentWarehouseApi(selectRows.value.map((t: CustomerServiceWaybill.ListRows) => t.id)).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            Message.success("操作成功!");
            searchHandle();
          }
        });
      }
    });
  };
  //恢复运单
  const recoverShipmentHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    recoverShipmentApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        Message.success("操作成功!");
        searchHandle();
      }
    });
  };

  return {
    searchHandle,
    getData,
    changeTabHandle,
    statusHandle,
    outOfWarehouseHandle,
    getStatisticsDataFn,
    requestFn,
    turnTurnShipmentWarehouseHandle,
    recoverShipmentHandle,
    getParams
  };
}
